package com.tanger.config;

import io.swagger.annotations.Api;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.ArrayList;
import java.util.List;


/**
 * @Descripton: swagger配置
 * @Author: Hchenbin
 * @Date:2022/05/06 17:20
 */
@Configuration
public class SwaggerConfiguration{

    @Bean
    public Docket allApi() {
        return createDocket("/tanger/**", "通用合集");
    }

    @Bean
    public Docket oauthApi() {
        return createDocket("/tanger/oauth/**", "认证合集");
    }

    @Bean
    public Docket commonApi() {
        return createDocket("/tanger/api/**", "移动端合集");
    }

    @Bean
    public Docket adminApi() {
        return createDocket("/tanger/bts/**", "管理端合集");
    }

    private Docket createDocket(String antPattern, String groupName) {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                .paths(PathSelectors.ant(antPattern))
                .build()
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts())
                .groupName(groupName);
    }


    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("BASE API")
                .contact(new Contact("Api.", null, null))
                .version("1.0")
                .build();
    }

    private List<SecurityScheme> securitySchemes() {
        //设置请求头信息
        List<SecurityScheme> result = new ArrayList<>();
        ApiKey apiKey = new ApiKey("Authorization", "Authorization", "header");
        result.add(apiKey);
        return result;
    }


    private List<SecurityContext> securityContexts() {
        List<SecurityContext> securityContexts = new ArrayList<>();
        securityContexts.add(SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.regex("^(?!auth).*$")).build());
        return securityContexts;
    }

    private List<SecurityReference> defaultAuth() {
        List<SecurityReference> result = new ArrayList<>();
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        result.add(new SecurityReference("Authorization", authorizationScopes));
        return result;
    }

}
